package com.lenovo.mso2o.service;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;

import com.lenovo.framework.rx.RxBus;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.entity.Order;
import com.lenovo.mso2o.entity.g.Notification;
import com.lenovo.mso2o.entity.g.NotificationDao;
import com.lenovo.mso2o.entity.g.SlaAlarm;
import com.lenovo.mso2o.entity.g.SlaAlarmDao;
import com.lenovo.mso2o.ui.MainActivity;
import com.lenovo.mso2o.ui.adapter.NotificationAdapter;
import com.lenovo.mso2o.util.SendNotification;
import com.lenovo.mso2o.util.Utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Scheduler;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by lenovo on 2016/5/12.
 */
public class SlaAlarmService extends Service {
    private static Scheduler.Worker worker;
    private SlaAlarmDao slaAlarmDao;
    private NotificationDao notificationDao;
    private static final String NEW_NOTIFICATION = "Refresh_Adapter";

    @Override
    public void onCreate() {
        super.onCreate();
        worker = Schedulers.io().createWorker();
        slaAlarmDao = MSApplication.getDaoSession().getSlaAlarmDao();
        notificationDao = MSApplication.getDaoSession().getNotificationDao();
        //逻辑是这样的
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //这里将所有的工单存入数据库
        startTimer();
        return super.onStartCommand(intent, flags, startId);
    }

    private void startTimer() {
        if (worker == null) {
            worker = Schedulers.io().createWorker();
        }
        worker.schedulePeriodically(new Action0() {
            @Override
            public void call() {
                //每隔10秒，扫描一次表，得到【已预约,待接单】的工单
                //看看notification这张表中是否有这个工单，若有什么也别做
                //若没有，1 发一个通知， 2 将工单存入通知表

                if (slaAlarmDao == null) {
                    slaAlarmDao = MSApplication.getDaoSession().getSlaAlarmDao();
                }
                //autoSignOrderDao.queryBuilder().where(AlarmTimeDao.Properties..lt(System.currentTimeMillis())).buildDelete().executeDeleteWithoutDetachingEntities();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        List<SlaAlarm> alarms = slaAlarmDao.queryBuilder().where(SlaAlarmDao.Properties.Desone.eq(getString(R.string.receiveorder)), SlaAlarmDao.Properties.Destwo.eq(getString(R.string.appoint))).list();
                        if (alarms != null && alarms.size() > 0) {
                            if (notificationDao == null) {
                                notificationDao = MSApplication.getDaoSession().getNotificationDao();
                            }
                            for (int i = alarms.size() -1; i >= 0; i--) {
                                SlaAlarm alarm = alarms.get(i);
                                String ticketId = alarm.getTickedid();
                                Date alarmDate = alarm.getAlarmtime();
                                Date overDate = alarm.getOvertime();
                                if(alarmDate == null || overDate == null){
                                    return;
                                }
                                //notification表中是否有ticketid, isAlarm = true的工单，若有，啥也别做，若没有... 哈哈哈
                                if(System.currentTimeMillis() >= overDate.getTime()){//当前时间大于超时时间
                                    //查看超时单
                                    List<Notification> listNotify = notificationDao.queryBuilder().where(NotificationDao.Properties.Title.eq(alarm.getTickedid()), NotificationDao.Properties.AlarmType.eq(getString(R.string.alarm_type_OVER))).list();
                                    if (listNotify.size() == MSConstants.OtherConstance.NOTIFICATION_EMPTY) {
                                        //说明表中没有，这时就要添加了
                                        //造一个notification, 插入表中
                                        //发一个预警通知re
                                        String content = getString(R.string.overtime_react) + "：\n编号为: " + ticketId + "工单在服务实施环节，需要您及时处理。";
                                        Notification notification = new Notification();
                                        notification.setContent(content);
                                        notification.setAlarmType(getString(R.string.alarm_type_OVER));
                                        notification.setTitle(ticketId);
                                        notification.setDesc(getString(R.string.overtime_react));
                                        notification.setType(NotificationAdapter.MESSAGETYPE.SLA_NOTIFY_ACTIVE_ORDER);
                                        notification.setDate(new Date());
                                        notificationDao.insert(notification);
                                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                                            @Override
                                            public void run() {
                                                RxBus rxBus = MSApplication.getRxBus();
                                                rxBus.send(NEW_NOTIFICATION);
                                            }
                                        });
                                        SendNotification.sendNotification(R.drawable.ic_launcher, getString(R.string.overtime_react), "编号为:" + ticketId + "工单在服务实施环节，需要您及时处理。", SlaAlarmService.this, true, R.string.auto_sign_pls, PendingIntent.FLAG_UPDATE_CURRENT, MainActivity.OPEN_ORDER_SIGN);
                                    } else {
                                        //表中已有，那啥也别做了
                                    }

                                }else if(System.currentTimeMillis() >= alarmDate.getTime()){//当前时间大于预警时间
                                    //查看预警单
                                    List<Notification> notifications = notificationDao.queryBuilder().where(NotificationDao.Properties.Title.eq(alarm.getTickedid()), NotificationDao.Properties.AlarmType.eq(getString(R.string.alarm_type_ALARM))).list();
                                    if (notifications.size() == MSConstants.OtherConstance.NOTIFICATION_EMPTY) {
                                        //说明表中没有，这时就要添加了
                                        //造一个notification, 插入表中
                                        //发一个预警通知
                                        String content = getString(R.string.overtime_alarm) + "：\n编号为: " + ticketId + "工单在服务实施环节，需要您及时处理。";
                                        final Notification notification = new Notification();
                                        notification.setContent(content);
                                        notification.setTitle(ticketId);
                                        notification.setAlarmType(getString(R.string.alarm_type_ALARM));
                                        notification.setDesc(getString(R.string.overtime_alarm));
                                        notification.setType(NotificationAdapter.MESSAGETYPE.SLA_NOTIFY_ACTIVE_ORDER);
                                        notification.setDate(new Date());
                                        notificationDao.insert(notification);
                                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                                            @Override
                                            public void run() {
                                                RxBus rxBus = MSApplication.getRxBus();
                                                rxBus.send(NEW_NOTIFICATION);
                                            }
                                        });
                                        SendNotification.sendNotification(R.drawable.ic_launcher, getString(R.string.overtime_alarm), "编号为:" + ticketId + "工单在服务实施环节，需要您及时处理。", SlaAlarmService.this, true, R.string.auto_sign_pls, PendingIntent.FLAG_UPDATE_CURRENT, MainActivity.OPEN_ORDER_SIGN);
                                    } else {
                                        //表中已有，那啥也别做了
                                    }
                                }

                            }
                            //最后如果notification表中数目多余200，要清空表
                            if(notificationDao != null && notificationDao.queryBuilder().list().size() > MSConstants.OtherConstance.NOTIFICATION_FULL){
                                notificationDao.deleteAll();
                            }
                        }
                    }
                }).start();

            }
        }, 5, 60, TimeUnit.SECONDS);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onDestroy() {
        if(worker != null){
            worker.unsubscribe();
            worker = null;
        }
        super.onDestroy();
    }
}
